import { defineStore } from "pinia";
import { defaultSetting, setLocaStore, setToken, reset } from './helper'
import { getUserInfo } from '@/api/index'
import { ElMessage } from 'element-plus'
import { store } from '@/store/helper'

export const useUserStore = defineStore('user-store', {
    state: defaultSetting,
    actions: {
        updateToken(token){
            this.token = token
            setToken(token)
            this.getUserInfo()
        },
        resetToken(){
            this.token = null
            this.userInfo = null
            reset()
        },
        getUserInfo(){
            getUserInfo().then(res => {
                if(res.code === 200){
                    this.userInfo = res.data
                    setLocaStore(JSON.stringify(this.userInfo))
                }else{
                    ElMessage.error(res.msg)
                }
            })
        },
    },
    getters: {
        isTeacher: (state) => state?.userInfo?.accountType === '2'
    }
})


export function useUserStoreWithOut() {
    return useUserStore(store)
}
